package com.hoshiicloud.marketmanagement.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.gson.Gson;
import com.hoshiicloud.common.exception.ServiceException;
import com.hoshiicloud.common.rpc.Response;
import com.hoshiicloud.goods.entity.sku.ProductManage;
import com.hoshiicloud.goods.param.sku.ProductManageAddParam;
import com.hoshiicloud.goods.param.sku.ProductManageQueryParam;
import com.hoshiicloud.market.param.activities.ActiviteGoodsDeleteDto;
import com.hoshiicloud.market.param.activities.ActivitiesProductManageQueryParam;
import com.hoshiicloud.marketmanagement.feign.GoodsService;
import com.hoshiicloud.marketmanagement.service.MarketManagementService;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import javax.validation.Valid;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.data.redis.connection.SortParameters.Order;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.query.SortQuery;
import org.springframework.data.redis.core.query.SortQueryBuilder;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestBody;

/**
 * @author MarkerCCC
 * @date 2019-09-18 - 11:23
 */
@Slf4j
@Service
public class MarketManagementServiceImpl implements MarketManagementService {

    private final RedisTemplate<String, Object> redisTemplate;
    private final GoodsService goodsService;

    public MarketManagementServiceImpl(RedisTemplate<String, Object> redisTemplate,
            GoodsService goodsService) {
        this.redisTemplate = redisTemplate;
        this.goodsService = goodsService;
    }

    @Override
    public void addTemporaryActivityGoods(List<ProductManage> productManageList, String temporaryGoodsRedisKey) {
        productManageList.forEach(productManageAdd -> {
            redisTemplate.opsForList().rightPush(temporaryGoodsRedisKey, productManageAdd);
            redisTemplate.expire(temporaryGoodsRedisKey, 3, TimeUnit.HOURS);
        });
    }

    @Override
    public Response queryProductManagePage(ActivitiesProductManageQueryParam activitiesProductManageQueryParam) {
        ProductManageQueryParam param = this.getProductManageQueryParam(activitiesProductManageQueryParam);
        return goodsService.page(param);
    }

    @Override
    public Response<List<ProductManage>> queryProductManageAll(ActivitiesProductManageQueryParam activitiesProductManageQueryParam) {
        ProductManageQueryParam param = this.getProductManageQueryParam(activitiesProductManageQueryParam);
        return goodsService.list(param);
    }

    @Override
    public List<ProductManage> getRedisDataPage(String temporaryGoodsRedisKey, Long pageNumber, Long pageSize) {
        if (pageNumber == null || pageNumber == 0) {
            pageNumber = 1L;
        }
        if (pageSize == null || pageSize == 0) {
            pageSize = 10L;
        }
        SortQueryBuilder<String> builder = SortQueryBuilder.sort(temporaryGoodsRedisKey);
        builder.by("*->skuId")
                .get("#")
                .alphabetical(false)
                .order(Order.DESC)
                .limit(pageNumber, pageSize);
        SortQuery<String> build = builder.build();
        log.error("{}", build);
        List<Object> cks = redisTemplate.sort(builder.build());
        return cks.stream().map(cksObj -> (ProductManage) cksObj).collect(Collectors.toList());
    }

    @Override
    public void deleteTemporaryActivityGoods(ActiviteGoodsDeleteDto activiteGoodsDeleteDto) {
        List<ProductManage> productManageList = activiteGoodsDeleteDto.getProductManageList();
        String temporaryGoodsRedisKey = activiteGoodsDeleteDto.getTemporaryGoodsRedisKey();
        productManageList.forEach(productManage -> redisTemplate.opsForList().remove(temporaryGoodsRedisKey, 1, productManage));
    }

    @Override
    public void deleteTemporaryActivityGoodsAll(ActiviteGoodsDeleteDto activiteGoodsDeleteDto) {
        redisTemplate.delete(activiteGoodsDeleteDto.getTemporaryGoodsRedisKey());
    }

    /**
     * 得到ProductManageQueryParam
     *
     * @param activitiesProductManageQueryParam activitiesProductManageQueryParam
     * @return ProductManageQueryParam
     */
    private ProductManageQueryParam getProductManageQueryParam(
            @RequestBody @Valid ActivitiesProductManageQueryParam activitiesProductManageQueryParam) {
        String temporaryGoodsRedisKey = activitiesProductManageQueryParam.getTemporaryGoodsRedisKey();
        Long size = redisTemplate.opsForList().size(temporaryGoodsRedisKey);
        List<Object> productManageAddParamObjList = redisTemplate.opsForList().range(temporaryGoodsRedisKey, 0, size - 1);
        // if (CollectionUtils.isNotEmpty(productManageAddParamObjList)) {
        //     throw new ServiceException("暂无数据");
        // }
        List<Long> skuIdList = productManageAddParamObjList.parallelStream().map(productManageAddParamObj -> {
            ProductManage productManage = (ProductManage) productManageAddParamObj;
            return productManage.getSkuId();
        }).collect(Collectors.toList());
        activitiesProductManageQueryParam.setBaseSkuIdList(skuIdList);
        ProductManageQueryParam param = new ProductManageQueryParam();
        BeanUtil.copyProperties(activitiesProductManageQueryParam, param);
        return param;
    }

}
